﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ServiceMonitor.Core;

namespace ServiceMonitor.Model
{
    public class ConfigManager
    {
        private readonly string _configPath;
        private readonly Action<string> _logger;

        public ConfigManager(string configPath, Action<string> logger)
        {
            _configPath = configPath;
            _logger = logger;
        }
        public List<MonitorConfig> LoadConfigs()
        {
            try
            {
                if (!File.Exists(_configPath))
                {
                    return new List<MonitorConfig>();
                }
                string json = File.ReadAllText(_configPath);
                return JsonConvert.DeserializeObject<List<MonitorConfig>>(json)
                    ?? new List<MonitorConfig>();
            }
            catch (Exception ex)
            {
                _logger?.Invoke($"Config load failed: {ex.Message}");
                return new List<MonitorConfig>();
            }
        }
        public void SaveConfigs(IEnumerable<MonitorConfig> configs)
        {
            try
            {
                string directory = Path.GetDirectoryName(_configPath);
                if (!Directory.Exists(directory) && !string.IsNullOrEmpty(directory))
                {
                    Directory.CreateDirectory(directory);
                }
                string json = JsonConvert.SerializeObject(configs.ToList(), Formatting.Indented);
                File.WriteAllText(_configPath, json);
            }
            catch (Exception ex)
            {
                _logger?.Invoke($"Config save failed: {ex.Message}");
            }
        }
    }
}
